package cn.ztydata.teachingsystem.heaven.dao.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * 资源下载量
 *
 * @author fanruiping
 * @since 2014-12-23
 */
@Repository
public class ResourceDownloadDao{

    protected static Logger logger = LoggerFactory.getLogger(BaseRedisDao.class); //日志记录器

    @Resource(name = "stringRedisTemplate")
    protected RedisTemplate redisTemplate; //sdr-Redis模版

    /**
     * 地址资源下载量
     * @param resourceId 资源编号
     * @return long
     *
     * @author fanruiping
     * @since 2014-12-23
     */
    public long incrCount(final long resourceId){
        ValueOperations<String,Integer> valueOperations = redisTemplate.opsForValue();

        logger.debug("递增资源下载量");

        return valueOperations.increment(KeyUtils.resourceDownloadCount(resourceId),1);
    }

    /**
     * 获取资源下载量
     * @param resourceId 资源编号
     * @return Integer
     *
     * @author fanruiping
     * @since 2014-12-23
     */
    public Integer getCount(final long resourceId){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();

        String count = valueOperations.get(KeyUtils.resourceDownloadCount(resourceId));

        if(null == count){
            logger.debug("count is null:null == count");

            valueOperations.set(KeyUtils.resourceDownloadCount(resourceId),"0");

            return 0;
        }

        logger.debug("return count");

        return Integer.parseInt(count);
    }
}
